package pers.w.chaptertalk.funs;

import android.content.Context;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.widget.Toast;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Random;

import pers.w.chaptertalk.R;

public class Fun {
    private static final String TAG = "FUN" ;

    public static HashMap<Integer, Object> SHARE_MAP = new HashMap<>();

    public static boolean hasAccount(Context context){
        String u = (String) Fun.SHARE_MAP.get(R.string.prompt_username);
        String p = (String) Fun.SHARE_MAP.get(R.string.prompt_password);
        if (u != null && p != null && u.length() >= 3) {
            return true;
        }else {
           if(context!=null) Toast.makeText(context,"请登录",Toast.LENGTH_SHORT).show();
            return false;
        }

    }

    public static boolean isDebug() {
        return false;
    }


    /**
     * int到byte[] 由高位到低位
     *
     * @param i 需要转换为byte数组的整行值。
     * @return byte数组
     */
    public static byte[] intToByteArray(int i) {
        byte[] result = new byte[4];
        result[0] = (byte) ((i >> 24) & 0xFF);
        result[1] = (byte) ((i >> 16) & 0xFF);
        result[2] = (byte) ((i >> 8) & 0xFF);
        result[3] = (byte) (i & 0xFF);
        return result;
    }

    /**
     * byte[]转int
     *
     * @param bytes 需要转换成int的数组
     * @return int值
     */
    public static int byteArrayToInt(byte[] bytes) {
        int value = 0;
        for (int i = 0; i < 4; i++) {
            int shift = (3 - i) * 8;
            value += (bytes[i] & 0xFF) << shift;
        }
        return value;
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp  https://www.jianshu.com/p/a895dbed1c3b
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }
    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
    //上面2个函数复制blog.csdn.net/alvinhuai/article/details/82790888
    public static File rootPath ;// "/storage/emulated/0/Android/data/pers.w.chaptertalk/"; //Environment.getExternalStorageDirectory().getAbsolutePath();



    public static boolean writeBitmap(File path, Bitmap bmp) {
        boolean success = false;
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(path);
            success = bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return success;
    }

    public static String getMD5(String plainText) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");//获取MD5实例
            md.update(plainText.getBytes());//此处传入要加密的byte类型值
            byte[] digest = md.digest();//此处得到的是md5加密后的byte类型值

            /*
               下边的运算就是自己添加的一些二次小加密，记住这个千万不能弄错乱，
                   否则在解密的时候，你会发现值不对的（举例：在注册的时候加密方式是一种，
                在我们登录的时候是不是还需要加密它的密码然后和数据库的进行比对，但是
            最后我们发现，明明密码对啊，就是打不到预期效果，这时候你就要想一下，你是否
             有改动前后的加密方式）
            */

            StringBuilder sb = new StringBuilder();
            for (byte b : digest) {

                if (b < 0)
                    b *= -1;//变成正数，否则hex是8位
                // if (i < 16)
                //   sb.append(0);
                sb.append(Integer.toHexString(b));//通过Integer.toHexString方法把值变为16进制
            }
            if (Fun.isDebug()) Log.d(TAG, "getMD5: "+sb.toString().length() + "\t"+sb.toString());
            return sb.toString();//从下标0开始，length目的是截取多少长度的值
        } catch (NoSuchAlgorithmException e) {
            if (Fun.isDebug())e.printStackTrace();
            return "???";
        }
    }


  @NotNull
  public   static String webEncrypted(@NotNull String username, String password){
        StringBuilder sb = new StringBuilder();
        byte x = 0;
        for (int b:username.getBytes() ) {
            b+=x;x++;
            if (b < 0)
                b *= -1;
            sb.append(b*2);
        }
        for (int b:password.getBytes() ) {
            b+=x;x++;
            if (b < 0)
                b *= -1;
            sb.append(b);
        }
        String u_p=sb.toString();
        sb.setLength(0);

        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();

        for (int i = 0; i < u_p.length(); i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }

        String randomStr = sb.toString();
        sb.setLength(0);
        for (int i = 0; i < u_p.length(); i++) {
            sb.append(randomStr.charAt(i));
            sb.append(u_p.charAt(i));
        }
        return sb.toString();
    }

    /**
     * 检查是否有网络
     * @param context
     * @return
     */
    public static boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager connectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivityManager != null){
                NetworkInfo mNetworkInfo = connectivityManager.getActiveNetworkInfo();
                if (mNetworkInfo != null) {
                    if (mNetworkInfo.isAvailable())
                        return true;
                }
            }
        }
        Toast.makeText(context,"没有网络，请检查", Toast.LENGTH_SHORT).show();
        return false;
    }

}
